//
//  WPTabbar.m
//  CaiPiao
//
//  Created by zhoup on 16/5/24.
//  Copyright © 2016年 zhoup. All rights reserved.
//

#import "WPTabbar.h"
#import "WPButton.h"

@interface WPTabbar()


@property(nonatomic,strong) UIButton *lastBtn;
@end

@implementation WPTabbar

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addButton:@"TabBar_LotteryHall" selectedImageName:@"TabBar_LotteryHall_selected" withTag:0];
        
        [self addButton:@"TabBar_Arena" selectedImageName:@"TabBar_Arena_selected" withTag:1];
        
        [self addButton:@"TabBar_Discovery" selectedImageName:@"TabBar_Discovery_selected" withTag:2];
        
        [self addButton:@"TabBar_History" selectedImageName:@"TabBar_History_selected" withTag:3];
        [self addButton:@"TabBar_MyLottery" selectedImageName:@"TabBar_MyLottery_selected" withTag:4];
    }
    return self;
}

-(void)addButton:(NSString *)imageName selectedImageName:(NSString *)selectedImageName withTag:(NSInteger)tag
{
    WPButton *btn = [WPButton buttonWithType:UIButtonTypeCustom];
    if (tag == 0) {
        self.lastBtn = btn;
    }
    [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:selectedImageName] forState:UIControlStateSelected];
    btn.tag = tag;
    [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:btn];
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    NSInteger count = self.subviews.count;
    
    CGFloat btnW = [UIScreen mainScreen].bounds.size.width / 5;
    for (int  i = 0; i <  count; i++) {
        WPButton *btn = (WPButton *)self.subviews[i];
        
        btn.x = btnW * i;
        btn.y = 0;
        btn.width = btnW;
        btn.height= self.height;
    }
    
}

-(void)btnClicked:(UIButton *)btn
{
    
    NSInteger from = self.lastBtn.tag;
    NSInteger to = btn.tag;
    
    self.lastBtn.selected = NO;
    btn.selected = YES;
    self.lastBtn = btn;
    
    if([self.delegate respondsToSelector:@selector(tabbar:fromTag:toTag:)])
    {
        [self.delegate tabbar:self fromTag:from toTag:to];
    }
}

@end
